package common

import (
	"bytes"
	"database/sql"
	"fmt"
	"gitchina/kly_service/data"
	"gitchina/kly_service/models"
	"gitchina/kly_service/util"
	"net/http"
)

var domain string
var connStr string
var runmode = "dev"
var passwd = "123456"

func InitCommon(connType int) {
	util.InitLogger(runmode)
	util.InitJms(runmode)
	data.InitOrm(runmode)
	models.AuthInit()
	if runmode == "dev" {
		domain = "localhost:8081"
	} else if runmode == "test" {
		domain = "139.196.39.90:8081"
	} else if runmode == "uat" {
		domain = "121.40.179.96:8081"
	}
	SwitchConn(connType)
}

func SwitchConn(connType int) {
	if connType == 1 {
		connStr = data.GetLogisticsConnStr()
	} else if connType == 2 {
		connStr = data.GetSocialConnStr()
	}
}

func Domain() string {
	return domain
}

func Passwd() string {
	return passwd
}

func New_Passwd() string {
	return "passwd"
}

func Version() string {
	return "1.0.0"
}

func Env() string {
	return runmode
}

func TruncateTables(tables ...string) {
	db, err := sql.Open("mysql", connStr)
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	for _, t := range tables {
		_, err = db.Exec(fmt.Sprintf("truncate table %s;", t))
	}
	if err != nil {
		panic(err.Error())
	}
}

func SqlExec(s string) {
	db, err := sql.Open("mysql", connStr)
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	_, err = db.Exec(s)
	if err != nil {
		panic(err.Error())
	}
}

func GetHttpRequest(method, api string, data []byte) *http.Request {
	req, _ := http.NewRequest(method, fmt.Sprintf("http://%s/v1/api/%s", Domain(), api), bytes.NewBuffer(data))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("version", Version())
	req.Header.Set("X-Real-Ip", "127.0.0.1")
	return req
}
